/**
 * @parma author ludan
 * @param explain login 登录界面
 */
import React, { useState } from 'react'
import { Form, Input, Button } from "antd";
import { useNavigate } from 'react-router-dom'
import RegisterModal from './Register';
import { login } from '@/requests'
import './index.less'
import { useStore } from '@/stores'

export interface baseLoginParamType {
  username: string;
  password: string;
}

const useLoginRequest = (): [boolean, (values: baseLoginParamType) => void] => {
  const [isLoading, setIsLoading] = useState(false);
  const navigate = useNavigate();
  const { userStore } = useStore();

  const handleSubmit = async (values: baseLoginParamType) => {
    setIsLoading(true);
    login({
      ...values,
      TXCODE: "login"
    }).then((response: any) => {
      setIsLoading(false);
      if (response) {
        userStore.setUserInfo(response.userInfo)
        sessionStorage.setItem("username", response.userInfo.username)
        sessionStorage.setItem("token", JSON.stringify(response.token))
        navigate("/Welcome");
      } else {
        setIsLoading(false);
      }
    }).catch(err => {
      setIsLoading(false);
    })
  };
  return [isLoading, handleSubmit]
}

const Login: React.FC = () => {
  const [isLoading, handleSubmit] = useLoginRequest();
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 注册跳转到注册页
  const handleClickRegistBtn = () => setIsModalOpen(true);

  return (
    <div className='login-container'>
      <Form onFinish={(values) => handleSubmit(values)} className="login-form">
        <div className="title-container">
          <h3 className="title">用户登录</h3>
        </div>
        <Form.Item
          name="username"
          rules={[{ required: true, message: "请输入用户名" }]}
        >
          <Input placeholder={"用户名"} type="text" id={"username"} className="inputheight" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input placeholder={"密码"} type="password" id={"password"} className="inputheight" />
        </Form.Item>
        <Form.Item>
          <Button className='sub-btn inputheight' loading={isLoading as boolean} htmlType="submit" type="primary">
            登录
          </Button>
          <span className='regist-btn' onClick={handleClickRegistBtn}>注册</span>
        </Form.Item>
      </Form>
      <RegisterModal isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} />
    </div>
  )
}

export default Login;

